package app.projeto.util;

import java.sql.Connection;
import java.sql.DriverManager;

public class DatabasePool {

	private static DatabasePool databasePool;
	
	private Connection connectionList[];
	private Integer maxConnections;
	private Integer currentConnection;
	private String host;
	private String port;
	private String databaseName;
	private String user;
	private String password;
	private String driver;
	private String url;
		
	private DatabasePool() throws Exception {
		this.maxConnections = 20;
		this.currentConnection = 0;
		this.connectionList = new Connection[this.maxConnections];
		this.host = "localhost";
		this.port = "5432";
		this.databaseName = "engenhariasw";
		this.user = "postgres";
		this.password = "postgres";
		this.driver = "org.postgresql.Driver";
		this.url = "jdbc:postgresql://" + this.host + ":" + this.port	+ "/" + this.databaseName;
		this.startConnections();
	}
	
	public static DatabasePool getInstance() throws Exception {
		if (databasePool == null) {
			databasePool = new DatabasePool();
		}
		return databasePool;
	}
	
	private void startConnections() throws Exception {
		for (int i = 0; i < this.maxConnections; i++) {
			this.connect(i);
		}
	}
	
	private void connect(Integer id) throws Exception {
		Class.forName(this.driver);
		this.connectionList[id] = DriverManager.getConnection(this.url, this.user, this.password);
		this.connectionList[id].setAutoCommit(false);
	}
	
	private boolean isConnected(Integer id) throws Exception {
		return (this.connectionList[id] != null) && 
				(!this.connectionList[id].isClosed());
	}
	
	public Connection getConnection() throws Exception {
		synchronized (DatabasePool.class) {
			Integer id = this.currentConnection;		
			if (!this.isConnected(id)) {
				this.connect(id);
			}
			this.currentConnection++;
			if (this.currentConnection >= this.maxConnections) {
				this.currentConnection = 0;
			}
			return this.connectionList[id];
		}
	}	
}